package com.zhy.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhy.usercenter.common.ErrorCode;
import com.zhy.usercenter.entity.User;
import com.zhy.usercenter.entity.UserLogin;
import com.zhy.usercenter.entity.UserRegister;
import com.zhy.usercenter.exception.BusinessException;
import com.zhy.usercenter.mapper.UserMapper;
import com.zhy.usercenter.service.UserServiceExpand;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.zhy.usercenter.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author 随缘而愈
 * @version 1.0
 * @description TODO
 * @date 22/3/2024 下午5:01
 */
@Slf4j
@Service("userServiceExpandImpl")
public class UserServiceExpandImpl extends ServiceImpl<UserMapper, User> implements UserServiceExpand {

    @Resource
    private UserMapper userMapper;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "yuan";

    /**
     * 默认头像地址
     */
    private static final String AVATAR_URL = "https://s11.ax1x.com/2024/02/02/pFQw2RS.jpg";



    /**
     * 用户注册
     * @param userRegister  用户注册请求体
     *
     * @return 新用户 id
     */
    @Override
    public long userRegisterExpand(UserRegister userRegister) {
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userRegister.getUserAccount());
        if (userMapper.exists(queryWrapper)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userRegister.getUserPassword()).getBytes());
        // 3. 插入数据
        User user = new User();
        userRegister.setUserPassword(encryptPassword);
        BeanUtils.copyProperties(userRegister,user);
        // 设置默认头像
        user.setAvatarUrl(AVATAR_URL);
        if (this.save(user)) {
            return user.getId();
        }
        return -1;
    }


    /**
     * 用户登录
     * @param userLogin  用户登录请求体
     * @param request
     *
     * @return 脱敏之后的用户信息
     */
    @Override
    public User userLoginExpand(UserLogin userLogin, HttpServletRequest request) {
        // 2. 加密
        String rePassword = DigestUtils.md5DigestAsHex((SALT + userLogin.getUserPassword()).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userLogin.getUserAccount());
        queryWrapper.eq("user_password", rePassword);
        User user = userMapper.selectOne(queryWrapper);
        if (userMapper.selectOne(queryWrapper) == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            return null;
        }
        // 3. 用户脱敏
        User safetyUser = getSafetyUser(user);
        // 4. 记录用户的登录态
        // TODO 后期优化使用 Sa-Token
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    @Override
    public User getSafetyUser(User originUser) {
        User safetyUser = new User();
        BeanUtils.copyProperties(originUser,safetyUser);
        return safetyUser;
    }


    /**
     * 更新用户
     *
     * @param user   用户
     * @return
     */
    @Override
    public boolean update(User user) {
        return false;
    }

    @Override
    public void userLogout(HttpServletRequest request) {
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
    }
}
